package com.cow.support.service;


import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cow.framework.core.base.BaseComponent;
import com.cow.framework.utils.encrypt.MD5Util;
import com.cow.support.dao.RoleDAO;
import com.cow.support.dao.UserDAO;
import com.cow.support.entity.Userinfo;
import com.cow.support.sys.exception.BusinessException;

@Service
public class UserService extends BaseComponent{
	@Autowired
	private UserDAO userDAO;
	@Autowired
	private RoleDAO roleDAO;

	public List<Userinfo> getAllUser() {
		return userDAO.findAll();
	}

	public Userinfo getUserByID(Integer userID){
		return (Userinfo)userDAO.findOne(userID);
	}

	public Userinfo getUserByAccountName(String accountName){
		return userDAO.findByAccountname(accountName);
	}
	
	public List<Userinfo> getUser(Userinfo userinfo) {
		return null;
	}

	public Integer saveUser(Userinfo userinfo) {		
		userinfo.setPassword(MD5Util.crypt(userinfo.getPassword().trim()));		
		userinfo.setRegisttime(new Date());
		if(userDAO.findByAccountname(userinfo.getAccountname())!=null){
			throw new BusinessException("账号不存在!");
		}
		userDAO.save(userinfo);
		return userinfo.getUserid();
	}
	
	public void updateUser(Userinfo userinfo,String accountname) {
		Userinfo user=userDAO.findByAccountname(userinfo.getAccountname());
		if(!accountname.equals(userinfo.getAccountname()) && user!=null){
			throw new BusinessException("账号不存在!");
		}
		if(user==null){
			userDAO.save(userinfo);			
		}else{
			try {
				PropertyUtils.copyProperties(user, userinfo);
			} catch (Exception e) {
				e.printStackTrace();
			}
			userDAO.save(user);
		}
	}
	public void updateUser(Userinfo userinfo) {
		userDAO.save(userinfo);	
	}
	

	public List<Userinfo> getUserByOrgID(Integer orgid) {
		return userDAO.findByOrgid(orgid);
	}
	

	public Userinfo getUserByUserID(Long userid) {
		return userDAO.findOne(userid);
	}

}
